//
//  DKSetTradeView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/4/19.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
typealias DKSetTradePasswordValue = (_ password:String)->()
class DKSetTradeView: UIView, UITextFieldDelegate{
    lazy var inputTextField:BaseTextField = {
        let textField = BaseTextField(changeView: self.superview, szBounds: CGRect.zero)
        textField.frame = CGRect(x: 25, y: 0, width: kSCREEN_WIDTH-50, height: 40)
        textField.backgroundColor = UIColor.clear
        textField.layer.masksToBounds = true
        textField.isSecureTextEntry = true
        textField.delegate = self
        textField.tintColor = UIColor.clear
        textField.textColor = UIColor.clear
        textField.font = UIFont.systemFont(ofSize: 30)
        textField.keyboardType = UIKeyboardType.numberPad
        textField.addTarget(self, action: #selector(textFiledEdingChanged), for: UIControlEvents.editingChanged)
        return textField
    }()
    
    
    var completion:DKSetTradePasswordValue?
    let KScreenUnit_W = UIScreen.main.bounds.size.width/375.0
    let kScreenUnit_H = UIScreen.main.bounds.size.height/667.0
    var kPasswordLength  = 6
    let kLineTag = 1000
    let kDotTag = 3000
    let textFieldWidth = UIScreen.main.bounds.size.width - 50 * 2 - 10 * 2
    let textFieldHeight = 35
    var openBool = false
    
    
    /// 初始化
    ///
    /// - Parameters:
    ///   - title: 标题
    ///   - cryptograph: 是否明文显示 true 明文 false密文
    ///   - block: 回调
    init(title:String, cryptograph:Bool ,length:Int = 6,height:CGFloat = 72.00 ,block:@escaping DKSetTradePasswordValue) {
        super.init(frame:CGRect(x: 0, y: height, width: kSCREEN_WIDTH, height: 40))
        kPasswordLength = length
        completion = block
        self.backgroundColor = UIColor.clear
        openBool = cryptograph
        self .addSubview(inputTextField)
        if length == 4 {
            inputTextField.frame = CGRect(x: 90, y: 0, width: kSCREEN_WIDTH-180, height: 40)
        }
        self.textFieldAddSubview();
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func textFieldAddSubview() -> Void {
        let letft = kPasswordLength == 4 ? 180 : 50
        var width = kSCREEN_WIDTH - CGFloat(letft) - CGFloat(40 * kPasswordLength)
        width = width / CGFloat(kPasswordLength-1)
        
        for i in 0..<kPasswordLength {
                var view = self.inputTextField.viewWithTag(kLineTag + i)
                
                if(view == nil) {
                    view = UIView()
                    view?.tag = kLineTag + i
                    view?.layer.borderColor = UIColor(hexStr:"#DDDDDD").cgColor
                    view?.layer.borderWidth = 0.5
                    view?.layer.cornerRadius = 5
                    inputTextField.addSubview(view!)
                    
                    let tap = UITapGestureRecognizer(target: self, action: #selector(giveUpFirstRespond))
                    tap .numberOfTouchesRequired = 1;
                    tap .numberOfTapsRequired = 1;
                    view?.addGestureRecognizer(tap)
                }
                
                view!.frame = CGRect(x: 0 + Double(width+40)*Double(i), y: Double(0), width: Double(40), height: Double(40))
            
            var dotLabel = self.inputTextField.viewWithTag(kOPBDTag+i)
            if dotLabel == nil {
               dotLabel = UILabel()
              (dotLabel as! UILabel).themeTextColor = ThemeManager.ThemeColorKeys.text1
               dotLabel?.tag = kDotTag + i
                view?.addSubview(dotLabel!)
            }
            dotLabel?.layer.masksToBounds = true;
            dotLabel?.layer.cornerRadius = 5;
            dotLabel?.backgroundColor = UIColor.black;
            if openBool {
                dotLabel?.backgroundColor = UIColor.clear
                dotLabel?.snp.makeConstraints({ (make) in
                    make.centerX.centerY.equalToSuperview()
                })
            }else {
                
                dotLabel?.snp.makeConstraints({ (make) in
                    make.centerX.centerY.equalToSuperview()
                    make.width.height.equalTo(10)
                })
            }
            dotLabel?.isHidden = true;
        }
        
        
    }
    
    @objc func giveUpFirstRespond() -> Void {
        inputTextField.becomeFirstResponder()
    }
    
    @objc func textFiledEdingChanged(textField:UITextField) -> Void {
        let length = inputTextField.text?.count;
        if length == kPasswordLength {
            self.endEditing(true)
            if (completion != nil) {
                self.completion!(inputTextField.text!)
            }
        }
        for i in 0 ..< kPasswordLength {
            let label = inputTextField.viewWithTag(kDotTag+i)
            if label != nil {
                if openBool && (label?.isHidden)!{
                    (label as! UILabel).text = textField.text?.last?.description
                }
                label?.isHidden = length! <= i
            }
        }
    }
    
   
    deinit {
        
        inputTextField.removeTarget(self, action: #selector(giveUpFirstRespond), for: UIControlEvents.editingChanged)
    }
    
    
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        
        let menuController = UIMenuController.shared
        menuController.isMenuVisible = false
        return false
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.endEditing(true)
    }
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
